import { Component, OnInit } from '@angular/core';
import { HttpService } from 'src/app/service/http.service';
import { ModalController } from '@ionic/angular';
import { CalendarModelComponent } from '../../../components/calendar-model/calendar-model.component';
import { ToastService } from 'src/app/service/toast.service';
import {TranslateService} from '@ngx-translate/core';

@Component({
  selector: 'app-doctor-appointments',
  templateUrl: './doctor-appointments.page.html',
  styleUrls: ['./doctor-appointments.page.scss'],
})
export class DoctorAppointmentsPage implements OnInit {
  appointDate: null;
  dataList = [];
  aCheckedList = [];
  orderTimeRange = [];
  sysLang = '';

  constructor(
    private httpService: HttpService,
    private modalController: ModalController,
    private toast: ToastService,
    private translate: TranslateService,
  ) {

  }

  async ngOnInit() {
    this.sysLang = this.translate.getBrowserCultureLang().toLowerCase();
    await this.getOrderTimeRange();
    await this.getTimeList();
  }

  public async selectDate() {
    const modal = await this.modalController.create({
      component: CalendarModelComponent,
      componentProps: {
        title: 'SelectDate',
        timeRange: false
      }
    });
    await modal.present();
    const { data } = await modal.onDidDismiss();
    if (!!data) {
      this.appointDate = data;
      await this.getTimeList();
    }
  }

  public async onResetOrderList() {
    this.appointDate = null;
    await this.getTimeList();
  }

  private async getOrderTimeRange() {
    const result: any = await this.httpService.get()
        .setPath('/pub/order/defaultTimeRange')
        .request();

    if (result.status === 0) {
      this.orderTimeRange = result.data;
    }
  }

  public async selectList(item) {
    if (item.isChecked) {
      this.aCheckedList.push(item.id);
    } else {
      for (let i = 0; i < this.aCheckedList.length; i++) {
        if (item.id === this.aCheckedList[i]) {
          this.aCheckedList.splice(i, 1);
        }
      }
    }
  }

  public async createAppointTime() {
    const modal = await this.modalController.create({
      component: CalendarModelComponent,
      componentProps: {
        title: 'SelectDate',
        timeRange: true,
        orderTimeRange: this.orderTimeRange
      }
    });
    await modal.present();
    const { data } = await modal.onDidDismiss();

    if (!!data) {
      const aUserId = localStorage.getItem('userId');

      const { event, startTime, endTime, timezoneOffset, orderDate } = data;
      if (event === 'create_one') {
        const result: any = await this.httpService.post()
            .setPath('/order/createHospitalOrder')
            .setBody({
              userId: aUserId,
              startTime,
              endTime,
              timezoneOffset
            })
            .request();

        if (result.status === 0) {
          this.toast.showToast('创建成功');
          await this.getTimeList();
        }
      } else if (event === 'create_all') {
        const result: any = await this.httpService.post()
            .setPath('/order/createHospitalOrderBatch')
            .setBody({
              userId: aUserId,
              orderDate,
              startTime,
              endTime,
              timezoneOffset
            })
            .request();

        if (result.status === 0) {
          this.toast.showToast('创建成功');
          await this.getTimeList();
        }
      }
    }
  }

  public async getTimeList() {
    const aUserId = localStorage.getItem('userId');

    const queryParams: any = {
      userId: aUserId,
      orderBooking: 1
    };

    queryParams.queryDate = this.httpService.getDatetimeString();

    if (this.appointDate) {
      queryParams.appointDate = this.httpService.getDateString(this.appointDate);
    }

    const result: any = await this.httpService.get()
      .setPath('/order/orderList')
      .setQuery(queryParams)
      .request();

    if (result.status === 0) {
      this.dataList = result.data;
      for (const item of this.dataList) {
        item.isChecked = false;
      }
    }
  }

  public async deleteTime() {
    const result: any = await this.httpService.delete()
      .setPath('/order/batchDelete')
      .setQuery({
        orderArray: this.aCheckedList.join(',')
      })
      .request();
    if (result.status === 0) {
      await this.getTimeList();

      if (this.sysLang === 'en-us') {
        this.toast.showToast('Successfully Deleted');
      } else {
        this.toast.showToast('删除成功');
      }
    }
  }
}
